#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2017/11/13 10:52
# @Author  : Yunhao.Cao
# @File    : data_storage.py
from __future__ import absolute_import, unicode_literals
import MySQLdb
import datetime

__author__ = 'Yunhao.Cao'

__ALL__ = ["DataStorage", ]


class DataStorage(object):
    def __init__(self):
        pass

    def save(self, **kwargs):
        pass


class FileStorage(DataStorage):
    def __init__(self, outfile):
        DataStorage.__init__(self)
        self._outfile = outfile

    def save(self, **kwargs):
        data = kwargs.get("data")
        with open(self._outfile, "a") as f:
            f.write("{}\n".format(data))


class MySqlStorage(DataStorage):
    def __init__(self, config, **kwargs):
        DataStorage.__init__(self)

        self._config = config

        self.db = MySQLdb.connect(**self._config)

    def __del__(self):
        self.close()

    def close(self):
        if self.db:
            self.db.close()

    def save(self, **kwargs):
        table = kwargs.get("table")
        raw_data = kwargs.get("raw_data")

        if not table or not isinstance(raw_data, (list, tuple)):
            raise

        def _to_sql_item(item):
            if isinstance(item, (int, float, long, bool,)):
                return "{}".format(item)
            elif isinstance(item, (basestring, datetime.date,)):
                return "'{}'".format(item)
            else:
                raise

        value_str = ", ".join(map(_to_sql_item, raw_data))

        sql = "INSERT INTO `{}` VALUES ({});".format(table, value_str)

        try:
            cursor = self.db.cursor()
            cursor.execute(sql)
            self.db.commit()
        except Exception as e:
            self.db.rollback()
            print("Exception = {}".format(e))


if __name__ == '__main__':
    _config = {
        'host': '192.168.118.250',
        'port': 3306,
        'user': 'intern',
        'passwd': '123456',
        'db': 'test_peewee',
        'charset': 'utf8',
    }

    test_data = (0, "test", datetime.datetime(1990, 1, 1))

    mysql = MySqlStorage(_config)
    mysql.save(table="person", raw_data=test_data)

    fs = FileStorage(outfile="./out/file_storage")
    fs.save(data=test_data)
